package products

import (
	"github.com/jinzhu/gorm"
	"time"
)

//CREATE TABLE `products` (
//  `id` int NOT NULL AUTO_INCREMENT,
//  `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//  `description` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
//  `cpu_cores` int DEFAULT NULL,
//  `memory` int DEFAULT NULL COMMENT '单位MB',
//  `storage` decimal(11,2) DEFAULT NULL COMMENT '存储大小 单位G',
//  `price` decimal(10,2) DEFAULT NULL,
//`tags` varchar(500) COLLATE utf8mb4_general_ci DEFAULT NULL,
//  `created_at` datetime DEFAULT NULL,
//  `updated_at` datetime DEFAULT NULL,
//  PRIMARY KEY (`id`)
//) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

type Products struct {
	Id              int               `json:"id" gorm:"primary_key;column:id"`
	Name            string            `json:"name" gorm:"column:name"`
	Description     string            `json:"description" gorm:"column:description"`
	CpuCores        int               `json:"cpu_cores" gorm:"column:cpu_cores"`
	Memory          int               `json:"memory" gorm:"column:memory"`
	Storage         float64           `json:"storage" gorm:"column:storage"`
	Price           float64           `json:"price" gorm:"column:price"`
	Tags            string            `json:"tags" gorm:"column:tags"`
	CreatedAt       time.Time         `json:"created_at" gorm:"column:created_at"`
	UpdatedAt       time.Time         `json:"updated_at" gorm:"column:updated_at"`
	ProductPackages []ProductPackages `json:"product_packages" gorm:"foreignkey:ProductId"`
	Type            int               `json:"type" gorm:"column:type"`
	CatId           int               `json:"cat_id" gorm:"column:cat_id"`
}

func (p *Products) TableName() string {
	return "products"
}
func (p *Products) GetById(db *gorm.DB) error {
	return db.Where("id = ?", p.Id).First(p).Error
}

func (p *Products) Create(db *gorm.DB) error {
	return db.Create(p).Error
}
func (p *Products) Update(db *gorm.DB) error {
	return db.Save(p).Error
}
func (p *Products) GetAllWithPackages(db *gorm.DB) ([]Products, error) {
	var products []Products
	return products, db.Preload("ProductPackages", "is_show = ?", 1).Where("status = ?", 1).Find(&products).Error
}

func (p *Products) GetByIdWithPackages(db *gorm.DB) error {
	return db.Preload("ProductPackages").Where("id = ?", p.Id).First(p).Error
}
